<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/dxl/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/dxl/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/dxl/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/dxl/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/dxl/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/dxl/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/dxl/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/dxl/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/dxl/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="面试题,">










<meta name="description" content="一、中间件1、中间的定义 1是介于request与response处理之间的一道处理过程，相对比较轻量级，并且在全局上改变django的输入与输出  2、中间件的5个方法 12345process_request(self,request)process_view(self, request, view_func, view_args, view_kwargs)process_template_r">
<meta name="keywords" content="面试题">
<meta property="og:type" content="article">
<meta property="og:title" content="Django">
<meta property="og:url" content="http://yoursite.com/2019/09/21/【内容回顾】03-2django - 副本/index.html">
<meta property="og:site_name" content="我的快乐时光">
<meta property="og:description" content="一、中间件1、中间的定义 1是介于request与response处理之间的一道处理过程，相对比较轻量级，并且在全局上改变django的输入与输出  2、中间件的5个方法 12345process_request(self,request)process_view(self, request, view_func, view_args, view_kwargs)process_template_r">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/images/04.png">
<meta property="og:image" content="http://yoursite.com/images/05.png">
<meta property="og:updated_time" content="2019-09-20T12:15:06.067Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Django">
<meta name="twitter:description" content="一、中间件1、中间的定义 1是介于request与response处理之间的一道处理过程，相对比较轻量级，并且在全局上改变django的输入与输出  2、中间件的5个方法 12345process_request(self,request)process_view(self, request, view_func, view_args, view_kwargs)process_template_r">
<meta name="twitter:image" content="http://yoursite.com/images/04.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/dxl/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/09/21/【内容回顾】03-2django - 副本/">





  <title>Django | 我的快乐时光</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/dxl/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的快乐时光</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/dxl/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/dxl/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/dxl/2019/09/21/【内容回顾】03-2django - 副本/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content>
      <meta itemprop="description" content>
      <meta itemprop="image" content="/dxl/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的快乐时光">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Django</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-21T14:59:54+08:00">
                2019-09-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/dxl/categories/面试题/" itemprop="url" rel="index">
                    <span itemprop="name">面试题</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/dxl/2019/09/21/【内容回顾】03-2django - 副本/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/dxl/2019/09/21/【内容回顾】03-2django - 副本/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="一、中间件"><a href="#一、中间件" class="headerlink" title="一、中间件"></a>一、中间件</h2><p>1、中间的定义</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">是介于request与response处理之间的一道处理过程，相对比较轻量级，并且在全局上改变django的输入与输出</span><br></pre></td></tr></table></figure>

<p>2、中间件的5个方法</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">process_request(self,request)</span><br><span class="line">process_view(self, request, view_func, view_args, view_kwargs)</span><br><span class="line">process_template_response(self,request,response)</span><br><span class="line">process_exception(self, request, exception)</span><br><span class="line">process_response(self, request, response)</span><br></pre></td></tr></table></figure>

<p>3、执行顺序</p>
<p><img src="/images/04.png" alt></p>
<p><img src="/images/05.png" alt></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">注意实现：</span><br><span class="line">process_response 每一个里面都要返回一个response对象，不然会报错</span><br></pre></td></tr></table></figure>

<h2 id="二、url路由"><a href="#二、url路由" class="headerlink" title="二、url路由"></a>二、url路由</h2><p>1、无名分组</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">路由：urlpatterns = [url(<span class="string">r'^articles/([0-9]&#123;4&#125;)/$'</span>, views.year_archive),]</span><br><span class="line">视图  <span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request,m)</span></span></span><br><span class="line"><span class="function">请求路径 /<span class="title">index</span>/2012/</span></span><br></pre></td></tr></table></figure>

<p>2、命名分组</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">路由：urlpatterns = [url(<span class="string">r'^articles/(?p&lt;year&gt;[0-9]&#123;4&#125;)/$'</span>, views.year_archive),]</span><br><span class="line">视图  <span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request,year)</span></span></span><br><span class="line">请求路径 /index/2012/year=2012</span><br></pre></td></tr></table></figure>

<p>3、路由分发</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">第一步：项目文件：</span><br><span class="line">urlpatterns = [</span><br><span class="line">   url(<span class="string">r'^admin/'</span>, admin.site.urls),</span><br><span class="line">   url(<span class="string">r'^blog/'</span>, include(<span class="string">'blog.urls'</span>)),  <span class="comment"># 可以包含其他的URLconfs文件</span></span><br><span class="line">   url(<span class="string">r'^app01/'</span>,include(<span class="string">'app01.urls'</span>)),  </span><br><span class="line">    <span class="comment">#别忘了要去app01这个应用下创建一个urls.py的文件，</span></span><br><span class="line">    <span class="comment">#凡是以app01开头的路径请求，都让它去找app01下的urls文件中去找对应的视图函数，</span></span><br><span class="line">    <span class="comment">#此时这个文件里面的那个app01路径不能用$结尾，因为如果写了$，就没办法比配上app01/后面的路径了</span></span><br><span class="line">]</span><br><span class="line">第二步：app01文件</span><br><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"><span class="comment">#from django.contrib import admin</span></span><br><span class="line"><span class="keyword">from</span> app01 <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    <span class="comment"># url(r'^admin/', admin.site.urls),</span></span><br><span class="line">    url(<span class="string">r'^articles/2003/'</span>, views.special_case_2003,&#123;<span class="string">'foo'</span>:<span class="string">'xxxxx'</span>&#125;),</span><br><span class="line">    url(<span class="string">r'^articles/(\d&#123;4&#125;)/(\d&#123;2&#125;)/'</span>, views.year_archive),</span><br><span class="line"></span><br><span class="line">]</span><br><span class="line">第三步：访问路径/app01/articles/<span class="number">2012</span>/<span class="number">05</span></span><br><span class="line"><span class="comment">#执行过程</span></span><br><span class="line"><span class="number">1</span>、浏览器发送请求 http://<span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>:<span class="number">8000</span>/app01/articles/<span class="number">2003</span>/</span><br><span class="line"><span class="number">2</span>、定位到项目里面的urls.py</span><br><span class="line"><span class="number">3</span>、定位到app01/</span><br><span class="line"><span class="number">4</span>、拿着articles/<span class="number">2003</span>/去app01里面的urls.py文件里面进行匹配</span><br><span class="line"><span class="number">5</span>、执行对应的函数</span><br></pre></td></tr></table></figure>

<p>4、别名和方向解析</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#urls.py</span></span><br><span class="line">url(<span class="string">r'^home'</span>, views.home, name=<span class="string">'home'</span>)</span><br><span class="line">url(<span class="string">r'^articles/([0-9]&#123;4&#125;)/$'</span>, views.year_archive, name=<span class="string">'news-year-archive'</span>), </span><br><span class="line"><span class="comment">#HTML：</span></span><br><span class="line">&#123;% url <span class="string">'home'</span> %&#125;  <span class="comment">#模板渲染的时候，被django解析成了这个名字对应的那个url，这个过程叫做反向解析</span></span><br><span class="line">&lt;a href="&#123;% url 'news-year-archive' yearvar %&#125;"&gt;&#123;&#123; yearvar &#125;&#125; Archive&lt;/a&gt;</span><br><span class="line"><span class="comment">#：views</span></span><br><span class="line"><span class="keyword">return</span> redirect(reverse(<span class="string">'news-year-archive'</span>, args=(year,)))</span><br></pre></td></tr></table></figure>

<p>5、命名空间</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#第一步：urls.py</span></span><br><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url, include</span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^app01/'</span>, include(<span class="string">'app01.urls'</span>, namespace=<span class="string">'app01'</span>)),</span><br><span class="line">    url(<span class="string">r'^app02/'</span>, include(<span class="string">'app02.urls'</span>, namespace=<span class="string">'app02'</span>)),</span><br><span class="line">]</span><br><span class="line"><span class="comment">#第二步：app01中的urls.py</span></span><br><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"><span class="keyword">from</span> app01 <span class="keyword">import</span> views</span><br><span class="line"> </span><br><span class="line">app_name = <span class="string">'app01'</span></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^(?P&lt;pk&gt;\d+)/$'</span>, views.detail, name=<span class="string">'detail'</span>)</span><br><span class="line">]</span><br><span class="line">app_name = <span class="string">'app02'</span></span><br><span class="line">urlpatterns = [</span><br><span class="line">    url(<span class="string">r'^(?P&lt;pk&gt;\d+)/$'</span>, views.detail, name=<span class="string">'detail'</span>)</span><br><span class="line">]</span><br><span class="line"><span class="comment">#第三步：模板中使用：</span></span><br><span class="line">&#123;% url <span class="string">'app01:detail'</span> pk=<span class="number">12</span> pp=<span class="number">99</span> %&#125;</span><br><span class="line"><span class="comment">#第三步：views中的函数中使用：</span></span><br><span class="line">v = reverse(<span class="string">'app01:detail'</span>, kwargs=&#123;<span class="string">'pk'</span>:<span class="number">11</span>&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="三、视图"><a href="#三、视图" class="headerlink" title="三、视图"></a>三、视图</h2><p>1、request对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">request.path_info   <span class="comment">#path</span></span><br><span class="line">request.path_info  <span class="comment"># path_info</span></span><br><span class="line">request.get_full_path()</span><br><span class="line">request.method</span><br><span class="line">request.META</span><br><span class="line">request.body</span><br><span class="line">request.files</span><br><span class="line">reequest.getlist(<span class="string">"xx"</span>)=[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>]</span><br><span class="line"></span><br><span class="line">request.get_host()</span><br><span class="line">request.get_port()</span><br><span class="line">HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt=<span class="string">''</span>, max_age=<span class="literal">None</span>)</span><br><span class="line">HttpRequest.is_secure()  <span class="comment">#请求是否安全</span></span><br><span class="line">HttpRequest.is_ajax()   <span class="comment">#是否是ajex请求</span></span><br></pre></td></tr></table></figure>

<p>2、response对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、HttpResponse</span><br><span class="line">    <span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse，JsonResponse</span><br><span class="line">    response = HttpResponse(<span class="string">"Here's the text of the Web page."</span>)</span><br><span class="line">    response = HttpResponse(<span class="string">"Text only, please."</span>, content_type=<span class="string">"text/plain"</span>)</span><br><span class="line"><span class="number">2</span>、JsonResponse</span><br><span class="line">	<span class="keyword">return</span> JsonResponse(&#123;<span class="string">"msg"</span>:<span class="string">"ok!"</span>&#125;)</span><br><span class="line">	response = JsonResponse([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], safe=<span class="literal">False</span>)</span><br><span class="line"><span class="number">3</span>、render</span><br><span class="line">	render(request, <span class="string">'myapp/index.html'</span>, &#123;<span class="string">'foo'</span>: <span class="string">'bar'</span>&#125;)</span><br><span class="line"><span class="number">4</span>、redirect</span><br><span class="line">	<span class="keyword">return</span> redirect(<span class="string">'/some/url/'</span>)</span><br><span class="line">	可以orm返回对象、视图名称、具体的网址</span><br></pre></td></tr></table></figure>

<p>3、fbv/cbv</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">FBV：</span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_view</span><span class="params">(request)</span>:</span></span><br><span class="line">     <span class="keyword">if</span> request.method == <span class="string">'GET'</span>:</span><br><span class="line">            <span class="keyword">return</span> HttpResponse(<span class="string">'OK'</span>)</span><br><span class="line"></span><br><span class="line">------------------------------------------------------------------------------------------------------------</span><br><span class="line">CBV：views.py和urls.py都要做相应的修改</span><br><span class="line">views:</span><br><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse</span><br><span class="line"><span class="keyword">from</span> django.views <span class="keyword">import</span> View</span><br><span class="line">  </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyView</span><span class="params">(View)</span>:</span></span><br><span class="line">      <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">            <span class="keyword">return</span> HttpResponse(<span class="string">'OK'</span>)</span><br><span class="line">urls:</span><br><span class="line"><span class="keyword">from</span> django.conf.urls <span class="keyword">import</span> url</span><br><span class="line"><span class="keyword">from</span> myapp.views <span class="keyword">import</span> MyView <span class="comment">#引入我们在views.py里面创建的类</span></span><br><span class="line">  </span><br><span class="line">urlpatterns = [</span><br><span class="line">     url(<span class="string">r'^index/$'</span>, MyView.as_view()), <span class="comment">#'^index/$'与写入的路径有关</span></span><br><span class="line">]</span><br><span class="line">cbv执行流程：</span><br><span class="line">Django的url是将一个请求分配给可调用的函数的，而不是一个<span class="class"><span class="keyword">class</span>。针对这个问题，<span class="title">class</span>-<span class="title">based</span> <span class="title">view</span>提供了一个<span class="title">as_view</span><span class="params">()</span>静态方法（也就是类方法），调用这个方法，会创建一个类的实例，然后通过实例调用<span class="title">dispatch</span><span class="params">()</span>方法，<span class="title">dispatch</span><span class="params">()</span>方法会根据<span class="title">request</span>的<span class="title">method</span>的不同调用相应的方法来处理<span class="title">request</span>（如<span class="title">get</span><span class="params">()</span>，``<span class="title">post</span><span class="params">()</span>等）。到这里，这些方法和<span class="title">function</span>-<span class="title">based</span> <span class="title">view</span>差不多了，要接收<span class="title">request</span>，得到一个<span class="title">response</span>返回。如果方法没有定义，会抛出<span class="title">HttpResponseNotAllowed</span>异常</span></span><br></pre></td></tr></table></figure>

<p>4、给视图函数加装饰器</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">wrapper</span><span class="params">(func)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">inner</span><span class="params">(*args, **kwargs)</span>:</span></span><br><span class="line">        start_time = time.time()</span><br><span class="line">        ret = func(*args, **kwargs)</span><br><span class="line">        end_time = time.time()</span><br><span class="line">        print(<span class="string">"used:"</span>, end_time-start_time)</span><br><span class="line">        <span class="keyword">return</span> ret</span><br><span class="line">    <span class="keyword">return</span> inner</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># FBV版添加班级</span></span><br><span class="line"><span class="meta">@wrapper</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_class</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"POST"</span>:</span><br><span class="line">        class_name = request.POST.get(<span class="string">"class_name"</span>)</span><br><span class="line">        models.Classes.objects.create(name=class_name)</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/class_list/"</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"add_class.html"</span>)</span><br><span class="line"><span class="keyword">from</span> django.views <span class="keyword">import</span> View</span><br><span class="line"><span class="keyword">from</span> django.utils.decorators <span class="keyword">import</span> method_decorator</span><br><span class="line"><span class="comment">#first：给单独的方法加装饰器</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AddClass</span><span class="params">(View)</span>:</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @method_decorator(wrapper)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">"add_class.html"</span>)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self, request)</span>:</span></span><br><span class="line">        class_name = request.POST.get(<span class="string">"class_name"</span>)</span><br><span class="line">        models.Classes.objects.create(name=class_name)</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/class_list/"</span>)</span><br><span class="line"><span class="comment">#second:给类中的所有方法加装饰器</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Login</span><span class="params">(View)</span>:</span></span><br><span class="line"><span class="meta">    @method_decorator(login_test)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">dispatch</span><span class="params">(self, request, *args, **kwargs)</span>:</span></span><br><span class="line">        print(<span class="string">'before'</span>)</span><br><span class="line">        obj = super(Login,self).dispatch(request, *args, **kwargs)</span><br><span class="line">        print(<span class="string">'after'</span>)</span><br><span class="line">        <span class="keyword">return</span> obj</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> render(request,<span class="string">'login.html'</span>)</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span><span class="params">(self,request)</span>:</span></span><br><span class="line">        print(request.POST.get(<span class="string">'user'</span>))</span><br><span class="line">        <span class="keyword">return</span> HttpResponse(<span class="string">'Login.post'</span>)</span><br><span class="line"><span class="comment">#third:直接添加在类上，后面的name表示只给get添加装饰器</span></span><br><span class="line"><span class="meta">@method_decorator(login_test, name='get')  #get是给get方法加</span></span><br><span class="line"><span class="meta">@method_decorator(login_test, name='post')  #post是给post方法加</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">IndexView</span><span class="params">(View)</span>:</span></span><br><span class="line">　　　　<span class="function"><span class="keyword">def</span> <span class="title">get</span><span class="params">(self,request)</span>：</span></span><br><span class="line"><span class="function">　　　　　　<span class="title">pass</span></span></span><br><span class="line"><span class="function">#总结：</span></span><br><span class="line"><span class="function">#1、给类添加是必须声明<span class="title">name</span></span></span><br></pre></td></tr></table></figure>

<h2 id="五、单标查询"><a href="#五、单标查询" class="headerlink" title="五、单标查询"></a>五、单标查询</h2><h3 id="5-1概念介绍"><a href="#5-1概念介绍" class="headerlink" title="5.1概念介绍"></a>5.1概念介绍</h3><p>1、使用orm的优势</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">　它实现了数据模型与数据库的解耦，即数据模型的设计不需要依赖于特定的数据库，通过简单的配置就可以轻松更换数据库，这极大的减轻了开发人员的工作量，不需要面对因数据库变更而导致的无效劳动</span><br></pre></td></tr></table></figure>

<p>2、字段</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">CharField</span><br><span class="line">IntegerField</span><br><span class="line">FloatField</span><br><span class="line">AutoField</span><br><span class="line">TextField</span><br></pre></td></tr></table></figure>

<p>3、settings配置</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">DATABASES = &#123;</span><br><span class="line">    <span class="string">'default'</span>: &#123;</span><br><span class="line">        <span class="string">'ENGINE'</span>: <span class="string">'django.db.backends.mysql'</span>,</span><br><span class="line">        <span class="string">'NAME'</span>:<span class="string">'bms'</span>,     　　 　  <span class="comment"># 要连接的数据库，连接前需要创建好</span></span><br><span class="line">        <span class="string">'USER'</span>:<span class="string">'root'</span>,　　　　　　  <span class="comment"># 连接数据库的用户名</span></span><br><span class="line">        <span class="string">'PASSWORD'</span>:<span class="string">''</span>,　　　　　　  <span class="comment"># 连接数据库的密码</span></span><br><span class="line">        <span class="string">'HOST'</span>:<span class="string">'127.0.0.1'</span>,       <span class="comment"># 连接主机，默认本级</span></span><br><span class="line">        <span class="string">'PORT'</span>：<span class="number">3306</span>    　　　     <span class="comment">#  端口 默认3306</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>4、对应关系</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">类      ---------&gt;表</span><br><span class="line">类对象   ----------&gt;行(记录)</span><br><span class="line">类属性   ----------&gt;表的字段（重点）</span><br></pre></td></tr></table></figure>

<p>5、附ORM字段与数据库实际字段的对应关系:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">　　<span class="string">'AutoField'</span>: <span class="string">'integer AUTO_INCREMENT'</span>,</span><br><span class="line"><span class="string">'BigAutoField'</span>: <span class="string">'bigint AUTO_INCREMENT'</span>,</span><br><span class="line"><span class="string">'BinaryField'</span>: <span class="string">'longblob'</span>,</span><br><span class="line"><span class="string">'BooleanField'</span>: <span class="string">'bool'</span>,</span><br><span class="line"><span class="string">'CharField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line"><span class="string">'CommaSeparatedIntegerField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line"><span class="string">'DateField'</span>: <span class="string">'date'</span>,</span><br><span class="line"><span class="string">'DateTimeField'</span>: <span class="string">'datetime'</span>,</span><br><span class="line"><span class="string">'DecimalField'</span>: <span class="string">'numeric(%(max_digits)s, %(decimal_places)s)'</span>,</span><br><span class="line"><span class="string">'DurationField'</span>: <span class="string">'bigint'</span>,</span><br><span class="line"><span class="string">'FileField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line"><span class="string">'FilePathField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line"><span class="string">'FloatField'</span>: <span class="string">'double precision'</span>,</span><br><span class="line"><span class="string">'IntegerField'</span>: <span class="string">'integer'</span>,</span><br><span class="line"><span class="string">'BigIntegerField'</span>: <span class="string">'bigint'</span>,</span><br><span class="line"><span class="string">'IPAddressField'</span>: <span class="string">'char(15)'</span>,</span><br><span class="line"><span class="string">'GenericIPAddressField'</span>: <span class="string">'char(39)'</span>,</span><br><span class="line"><span class="string">'NullBooleanField'</span>: <span class="string">'bool'</span>,</span><br><span class="line"><span class="string">'OneToOneField'</span>: <span class="string">'integer'</span>,</span><br><span class="line"><span class="string">'PositiveIntegerField'</span>: <span class="string">'integer UNSIGNED'</span>,</span><br><span class="line"><span class="string">'PositiveSmallIntegerField'</span>: <span class="string">'smallint UNSIGNED'</span>,</span><br><span class="line"><span class="string">'SlugField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line"><span class="string">'SmallIntegerField'</span>: <span class="string">'smallint'</span>,</span><br><span class="line"><span class="string">'TextField'</span>: <span class="string">'longtext'</span>,</span><br><span class="line"><span class="string">'TimeField'</span>: <span class="string">'time'</span>,</span><br><span class="line"><span class="string">'UUIDField'</span>: <span class="string">'char(32)'</span>,</span><br></pre></td></tr></table></figure>

<h3 id="5-2操作"><a href="#5-2操作" class="headerlink" title="5.2操作"></a>5.2操作</h3><p>1、添加表记录</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#frist：</span></span><br><span class="line">book_obj=Book(title=<span class="string">"python葵花宝典"</span>,state=<span class="literal">True</span>,price=<span class="number">100</span>,publish=<span class="string">"苹果出版社"</span>,pub_date=<span class="string">"2012-12-12"</span>)</span><br><span class="line">book_obj.save()</span><br><span class="line"><span class="comment">#second:用的较多</span></span><br><span class="line">book_obj=Book.objects.create(title=<span class="string">"python葵花宝典"</span>,state=<span class="literal">True</span>,price=<span class="number">100</span>,publish=<span class="string">"苹果出版社"</span>,pub_date=<span class="string">"2012-12-12"</span>)</span><br><span class="line">或</span><br><span class="line">dic1 = &#123;<span class="string">'title'</span>:<span class="string">'linux'</span>,<span class="string">'state'</span>=<span class="literal">True</span>,<span class="string">'price'</span>:<span class="number">100</span>,<span class="string">'publish'</span>=<span class="string">'2018-12-12'</span>&#125;</span><br><span class="line">book.objects.create(**dic1)</span><br><span class="line"><span class="comment">#third 批量插入</span></span><br><span class="line">book_list = []</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">10</span>):</span><br><span class="line">    bk_obj = models.Book(</span><br><span class="line">            name=<span class="string">'chao%s'</span>%i,</span><br><span class="line">            addr=<span class="string">'北京%s'</span>%i</span><br><span class="line">    )</span><br><span class="line">    book_list.append(bk_obj)</span><br><span class="line">models.Book.objects.bulk_create(book_list) <span class="comment">#批量插入，速度快</span></span><br><span class="line"><span class="comment">#update_or_create 有就创建，没有就跟新</span></span><br><span class="line">obj,created = models.UserToken.objects.update_or_create(</span><br><span class="line">    user=user, <span class="comment"># 查找筛选条件</span></span><br><span class="line">    defaults=&#123; <span class="comment"># 添加或者更新的数据</span></span><br><span class="line">　　　　　　<span class="string">"token"</span>:random_str,</span><br><span class="line">　　　　&#125;</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<p>2、查询记录</p>
<p>1)13个api</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#13个api</span></span><br><span class="line">all()   filter(**kwargs)   结果是queryset类型</span><br><span class="line">get(**kwargs)  行记录对象</span><br><span class="line">values(*field) ValueQuerySet values(*field) 元组序列</span><br><span class="line">distinct() <span class="comment">#values和values_list得到的queryset类型的数据来调用，从返回结果中剔除重复纪录</span></span><br><span class="line">first()  last()  exists() count() order_by reverse()<span class="comment">#有queryset数据类型调用</span></span><br><span class="line"><span class="comment">#注意事项:</span></span><br><span class="line">all_books=models.Book.objects.all().values(<span class="string">'price'</span>).distinct()<span class="comment">#只能用于valuse和values_list进行去重</span></span><br></pre></td></tr></table></figure>

<p>2)基于双下划线的模糊查询</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Book.objects.filter(price__in=[<span class="number">100</span>,<span class="number">200</span>,<span class="number">300</span>]) <span class="comment">#price值等于这三个里面的任意一个的对象</span></span><br><span class="line">Book.objects.filter(price__gt=<span class="number">100</span>)  <span class="comment">#大于，大于等于是price__gte=100，别写price&gt;100，这种参数不支持</span></span><br><span class="line">Book.objects.filter(price__lt=<span class="number">100</span>)</span><br><span class="line">Book.objects.filter(price__range=[<span class="number">100</span>,<span class="number">200</span>])  <span class="comment">#sql的between and，大于等于100，小于等于200</span></span><br><span class="line">Book.objects.filter(title__contains=<span class="string">"python"</span>)  <span class="comment">#title值中包含python的</span></span><br><span class="line">Book.objects.filter(title__icontains=<span class="string">"python"</span>) <span class="comment">#不区分大小写</span></span><br><span class="line">Book.objects.filter(title__startswith=<span class="string">"py"</span>) <span class="comment">#以什么开头，istartswith  不区分大小写</span></span><br><span class="line">Book.objects.filter(pub_date__year=<span class="number">2012</span>)</span><br></pre></td></tr></table></figure>

<p>3、删</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">model_obj.delete()</span><br><span class="line">Entry.objects.all().delete(）</span><br><span class="line">如果不想级联删除，可以设置为:</span><br><span class="line">pubHouse = models.ForeignKey(to=<span class="string">'Publisher'</span>, on_delete=models.SET_NULL, blank=<span class="literal">True</span>, null=<span class="literal">True</span>)</span><br></pre></td></tr></table></figure>

<p>4、修改表纪律</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Book.objects.filter(title__startswith=<span class="string">"py"</span>).update(price=<span class="number">120</span>)</span><br><span class="line"><span class="comment">#update只能是querset类型才能调用，model对象不能直接调用更新方法，所以使用get方法获取对象的时候是不能update的。</span></span><br></pre></td></tr></table></figure>

<h2 id="六、多表查询"><a href="#六、多表查询" class="headerlink" title="六、多表查询"></a>六、多表查询</h2><h3 id="6-1表的创建"><a href="#6-1表的创建" class="headerlink" title="6.1表的创建"></a>6.1表的创建</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、一对一关系的建立</span><br><span class="line">authorDetail=models.OneToOneField(to=<span class="string">"AuthorDetail"</span>,to_field=<span class="string">"nid"</span>,on_delete=models.CASCADE)</span><br><span class="line"><span class="number">2</span>、一对多</span><br><span class="line">publish=models.ForeignKey(to=<span class="string">"Publish"</span>,to_field=<span class="string">"nid"</span>,on_delete=models.CASCADE) </span><br><span class="line"><span class="number">3</span>、多对多（常采用以下方式）</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    title = models.CharField(max_length=<span class="number">32</span>, verbose_name=<span class="string">"书名"</span>)</span><br><span class="line"><span class="comment"># 通过ORM自带的ManyToManyField自动创建第三张表</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Author</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    name = models.CharField(max_length=<span class="number">32</span>, verbose_name=<span class="string">"作者姓名"</span>)</span><br><span class="line">    books = models.ManyToManyField(to=<span class="string">"Book"</span>, related_name=<span class="string">"authors"</span>)</span><br></pre></td></tr></table></figure>

<h3 id="6-2表的基本操作"><a href="#6-2表的基本操作" class="headerlink" title="6.2表的基本操作"></a>6.2表的基本操作</h3><p>1、数据的增加</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">一对一</span><br><span class="line">方式<span class="number">1</span>:</span><br><span class="line">   publish_obj=Publish.objects.get(nid=<span class="number">1</span>) <span class="comment">#拿到nid为1的出版社对象</span></span><br><span class="line">   book_obj=Book.objects.create(title=<span class="string">"金瓶眉"</span>,publishDate=<span class="string">"2012-12-12"</span>,price=<span class="number">100</span>,publish=publish_obj) </span><br><span class="line">    <span class="comment">#出版社对象作为值给publish，过程就是自动将publish字段变成publish_id,然后将publish_obj的id给取出来赋值给publish_id字段,如果不是publish类的对象肯定会报错的</span></span><br><span class="line">方式<span class="number">2</span>:</span><br><span class="line">   book_obj=Book.objects.create(title=<span class="string">"金瓶眉"</span>,publishDate=<span class="string">"2012-12-12"</span>,price=<span class="number">100</span>,publish_id=<span class="number">1</span>)　　</span><br><span class="line">    <span class="comment">#直接可以写id值，注意字段属性的写法和上面不同，这个是publish_id=xxx，上面是publish=xxx。</span></span><br><span class="line">    </span><br><span class="line">多对多/一对多：</span><br><span class="line">   方式一：</span><br><span class="line">　　<span class="comment"># 生成的书籍对象</span></span><br><span class="line">    book_obj=Book.objects.create(title=<span class="string">"追风筝的人"</span>,price=<span class="number">200</span>,publishDate=<span class="string">"2012-11-12"</span>,publish_id=<span class="number">1</span>)</span><br><span class="line">    <span class="comment"># 作者对象 module对象</span></span><br><span class="line">    yuan=Author.objects.filter(name=<span class="string">"yuan"</span>).first() </span><br><span class="line">    egon=Author.objects.filter(name=<span class="string">"alex"</span>).first()</span><br><span class="line">    <span class="comment">#添加两条数据</span></span><br><span class="line">    book_obj.authors.add(yuan,egon)</span><br><span class="line">    或book_obj.authors.add(*[])</span><br><span class="line">    <span class="comment">#book_obj是书籍对象，authors是book表里面那个多对多的关系字段名称。</span></span><br><span class="line">    <span class="comment">#执行过程：orm就是先通过book_obj的authors属性找到第三张表，然后将book_obj的id值和两个作者对象的id值组合成两条记录添加到第三张表里面去</span></span><br><span class="line">　　方式二</span><br><span class="line">　　　　book_obj.authors.add(<span class="number">1</span>，<span class="number">2</span>)</span><br><span class="line">　　　　book_obj.authors.add(*[<span class="number">1</span>，<span class="number">2</span>]) </span><br><span class="line">    <span class="comment">#这种方式用的最多，因为一般是给用户来选择，用户选择是多选的，选完给你发送过来的就是一堆的id值</span></span><br><span class="line"> 注意事项：</span><br><span class="line">    <span class="number">1</span>、多对多一般在前端页面上使用的时候是多选下拉框的样子来给用户选择多个数据，这里可以让用户选择多个书籍，多个作者</span><br><span class="line">    <span class="number">2</span>、通过orm间接的给第三张表添加数据，也可以通过语句直接给第三张表添加数据</span><br></pre></td></tr></table></figure>

<p>2、数据的删除</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、一对一</span><br><span class="line">    models.Author.objects.filter(id=<span class="number">3</span>).delete()</span><br><span class="line"><span class="number">2</span>、一对多</span><br><span class="line">    models.Book.objects.filter(id=<span class="number">1</span>).delete()</span><br><span class="line"><span class="number">3</span>、多对多</span><br><span class="line">    book_obj = models.Book.objects.filter(nid=<span class="number">4</span>)[<span class="number">0</span>]</span><br><span class="line">    book_obj.authors.remove(<span class="number">2</span>) </span><br><span class="line">    <span class="comment"># 将第三张表中的这个book_obj对象对应的那个作者id为2的那条记录删除</span></span><br><span class="line">    book_obj.authors.clear()</span><br><span class="line">    <span class="comment">#先清除掉所有的关系数据，然后只给这个书对象绑定这个id为2的作者，所以只剩下一条记录 </span></span><br><span class="line">    book_obj.authors.set(<span class="string">'2'</span>)</span><br><span class="line">    book_obj.authors.set([<span class="string">'1'</span>,])</span><br></pre></td></tr></table></figure>

<p>3、表的修改</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、一对一</span></span><br><span class="line">models.Author.objects.filter(id=<span class="number">3</span>).update(age=<span class="number">66</span>)</span><br><span class="line"><span class="comment">#2、一对多</span></span><br><span class="line">models.Book.objects.filter(id=<span class="number">2</span>).update(price=<span class="number">998</span>)</span><br><span class="line"><span class="comment">#3、多对多</span></span><br><span class="line">方式一：</span><br><span class="line">data = &#123;<span class="string">'title'</span>:<span class="string">'xxx'</span>,<span class="string">'price'</span>:<span class="number">100</span>&#125; <span class="comment">#这个书籍对象更新后的数据</span></span><br><span class="line">models.Book.objects.filter(id=n).update(**data) <span class="comment">#将新数据更新到原来的记录中</span></span><br><span class="line">方式二：</span><br><span class="line">book_obj = models.Book.objects.get(id=<span class="number">1</span>) <span class="comment">#获取一个书籍对象</span></span><br><span class="line">bai = author(<span class="string">'name'</span>:<span class="string">'xiaobai'</span>，<span class="string">'age'</span>:<span class="number">18</span>)</span><br><span class="line">hei = author(<span class="string">'name'</span>:<span class="string">'xiaobai'</span>，<span class="string">'age'</span>:<span class="number">18</span>)</span><br><span class="line">author_list =[bai,hei]</span><br><span class="line">book_obj.authors.set(author_list) <span class="comment">#将数据和作者的多对多关系加上</span></span><br></pre></td></tr></table></figure>

<p>4、数据的查找</p>
<p>1）基于对象的跨表查询</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">一对一查询</span><br><span class="line"></span><br><span class="line">正向查询</span><br><span class="line">egon=Author.objects.filter(name=<span class="string">"egon"</span>).first()</span><br><span class="line">print(egon.authorDetail.telephone) </span><br><span class="line">egon.authorDeail</span><br><span class="line"><span class="comment">#就拿到了这个对象，因为一对一找到的就是一条记录，</span></span><br><span class="line"><span class="comment">#注意写法：作者对象.字段名,就拿到了那个关联对象</span></span><br><span class="line"></span><br><span class="line">方向查询</span><br><span class="line"><span class="comment"># 查询所有住址在北京的作者的姓名</span></span><br><span class="line">authorDet=AuthorDetail.objects.filter(addr=<span class="string">"beijing"</span>)[<span class="number">0</span>]</span><br><span class="line">authorDet.author.name</span><br><span class="line"></span><br><span class="line">一对多查询：</span><br><span class="line">正向查询：</span><br><span class="line"><span class="comment"># ----查询主键为1的书籍的出版社所在的城市</span></span><br><span class="line">book_obj=Book.objects.filter(pk=<span class="number">1</span>).first()</span><br><span class="line">print(book_obj.publish.city) </span><br><span class="line"><span class="comment"># book_obj.publish 是主键为1的书籍对象关联的出版社对象， </span></span><br><span class="line"><span class="comment"># 方法：book对象.外键字段名称</span></span><br><span class="line">方向查询：</span><br><span class="line">publish=Publish.objects.get(name=<span class="string">"苹果出版社"</span>)</span><br><span class="line">book_list=publish.book_set.all()    </span><br><span class="line"><span class="keyword">for</span> book_obj <span class="keyword">in</span> book_list:</span><br><span class="line">    print(book_obj.title)</span><br><span class="line"><span class="comment">#publish.book_set.all() : 与苹果出版社关联的所有书籍对象集合，</span></span><br><span class="line"><span class="comment">#写法：小写的表名_set.all()，得到queryset类型数据</span></span><br><span class="line"></span><br><span class="line">多对多查询</span><br><span class="line">正向查询</span><br><span class="line"><span class="comment"># 金瓶眉所有作者的名字以及手机号</span></span><br><span class="line">book_obj=Book.objects.filter(title=<span class="string">"金瓶眉"</span>).first()</span><br><span class="line">authors=book_obj.authors.all()</span><br><span class="line"><span class="keyword">for</span> author_obj <span class="keyword">in</span> authors:</span><br><span class="line">     print(author_obj.name,author_obj.authorDetail.telephone)</span><br><span class="line">方向查询</span><br><span class="line"><span class="comment"># 查询egon出过的所有书籍的名字</span></span><br><span class="line">author_obj=Author.objects.get(name=<span class="string">"egon"</span>)</span><br><span class="line">book_list=author_obj.book_set.all()        <span class="comment">#与egon作者相关的所有书籍</span></span><br><span class="line"><span class="keyword">for</span> book_obj <span class="keyword">in</span> book_list:</span><br><span class="line">    print(book_obj.title)</span><br><span class="line"></span><br><span class="line">补充related_name：</span><br><span class="line">    ForeignKey() 和ManyToManyField的定义中设置 related_name 的值来覆写 FOO_set 的名称。</span><br><span class="line">    例如，如果 Article model 中做一下更改：</span><br><span class="line">    publish = ForeignKey(Blog, related_name=<span class="string">'bookList'</span>)</span><br><span class="line">    <span class="comment">#  查询人民出版社出版过的所有书籍的名字与价格(一对多)</span></span><br><span class="line">    <span class="comment"># 反向查询 不再按表名:book,而是related_name:bookList</span></span><br><span class="line">    queryResult=Publish.objects</span><br><span class="line">　　　　　　　　　　　　　　.filter(name=<span class="string">"人民出版社"</span>)</span><br><span class="line">　　　　　　　　　　　　　　.values_list(<span class="string">"bookList__title"</span>,<span class="string">"bookList__price"</span>)</span><br></pre></td></tr></table></figure>

<p>2）基于对象的双下划线查询</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">一对查询</span><br><span class="line">    <span class="comment"># 查询yuan的手机号</span></span><br><span class="line">    <span class="comment"># 正向查询</span></span><br><span class="line">    ret=Author.objects.filter(name=<span class="string">"yuan"</span>).values(<span class="string">"authordetail__telephone"</span>)</span><br><span class="line">    <span class="comment"># 反向查询</span></span><br><span class="line">    ret=AuthorDetail.objects.filter(author__name=<span class="string">"yuan"</span>).values(<span class="string">"telephone"</span>)</span><br><span class="line">一对多查询</span><br><span class="line"><span class="comment"># 练习:  查询苹果出版社出版过的所有书籍的名字与价格(一对多) </span></span><br><span class="line">    <span class="comment"># 正向查询 按字段:publish</span></span><br><span class="line">    queryResult=Book.objects</span><br><span class="line">　　　　　　　　　　　　.filter(publish__name=<span class="string">"苹果出版社"</span>) </span><br><span class="line">    <span class="comment">#通过__告诉orm将book表和publish表进行join，然后找到所有记录中publish.name='苹果出版社'的记录（注意publish是属性名称），然后select book.title,book.price的字段值</span></span><br><span class="line">　　　　　　　　　　　　.values_list(<span class="string">"title"</span>,<span class="string">"price"</span>) <span class="comment">#values或者values_list</span></span><br><span class="line">    <span class="comment"># 反向查询 按表名:book</span></span><br><span class="line">    queryResult=Publish.objects</span><br><span class="line">　　　　　　　　　　　　　　.filter(name=<span class="string">"苹果出版社"</span>)</span><br><span class="line">　　　　　　　　　　　　　　.values_list(<span class="string">"book__title"</span>,<span class="string">"book__price"</span>)</span><br><span class="line">多对多查询</span><br><span class="line"><span class="comment"># 练习: 查询yuan出过的所有书籍的名字(多对多)</span></span><br><span class="line">​</span><br><span class="line">    <span class="comment"># 正向查询 按字段:authors:</span></span><br><span class="line">    queryResult=Book.objects</span><br><span class="line">　　　　　　　　　　　　.filter(authors__name=<span class="string">"yuan"</span>)</span><br><span class="line">　　　　　　　　　　　　.values_list(<span class="string">"title"</span>)</span><br><span class="line">    <span class="comment"># 反向查询 按表名:book</span></span><br><span class="line">    queryResult=Author.objects</span><br><span class="line">　　　　　　　　　　　　　　.filter(name=<span class="string">"yuan"</span>)</span><br><span class="line">　　　　　　　　　　　　　　.values_list(<span class="string">"book__title"</span>,<span class="string">"book__price"</span>)</span><br></pre></td></tr></table></figure>

<p>3）聚合查询、分组查询</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#1、聚合</span></span><br><span class="line">aggregate(*args, **kwargs)</span><br><span class="line"><span class="comment"># 计算所有图书的平均价格</span></span><br><span class="line">first：一个聚合</span><br><span class="line"> <span class="keyword">from</span> django.db.models <span class="keyword">import</span> Avg</span><br><span class="line"> Book.objects.all().aggregate(Avg(<span class="string">'price'</span>)) <span class="comment">#或者给它起名字：aggretate(a=Avg('price'))</span></span><br><span class="line"> &#123;<span class="string">'price__avg'</span>: <span class="number">34.35</span>&#125;</span><br><span class="line">　　aggregate()是一个字典QuerySet 的一个终止子句，意思是说，它返回一个包含一些键值对的字典。</span><br><span class="line">secodnd:多个聚合</span><br><span class="line"><span class="keyword">from</span> django.db.models <span class="keyword">import</span> Avg, Max, Min</span><br><span class="line">Book.objects.aggregate(Avg(<span class="string">'price'</span>), Max(<span class="string">'price'</span>), Min(<span class="string">'price'</span>))  </span><br><span class="line"><span class="comment">#count('id'),count(1)也可以统计个数,</span></span><br><span class="line">&#123;<span class="string">'price__avg'</span>: <span class="number">34.35</span>, <span class="string">'price__max'</span>: Decimal(<span class="string">'81.20'</span>), <span class="string">'price__min'</span>: Decimal(<span class="string">'12.99'</span>)&#125;</span><br><span class="line"><span class="comment">#2、分组</span></span><br><span class="line"><span class="comment">#单标分组</span></span><br><span class="line">select dep,Count(*) <span class="keyword">from</span> emp group by dep;</span><br><span class="line">emp.objects.values(<span class="string">"dep"</span>).annotate(c=Count(<span class="string">"id"</span>)</span><br><span class="line"><span class="comment">#多表分组</span></span><br><span class="line"> select dep.name,Count(*) <span class="keyword">from</span> emp left join dep on emp.dep_id=dep.id group by dep.id</span><br><span class="line"> dep.objetcs.values(<span class="string">"id"</span>).annotate(c=Count(<span class="string">"emp"</span>)).values(<span class="string">"name"</span>,<span class="string">"c"</span>)</span><br><span class="line"> ret = models.Emp.objects.values(<span class="string">'dep_id'</span>,<span class="string">'name'</span>).annotate(a=Count(<span class="number">1</span>))</span><br></pre></td></tr></table></figure>

<p>4)F查询和q查询</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#f查询</span></span><br><span class="line">查询评论数大于收藏数的书籍</span><br><span class="line">  <span class="keyword">from</span> django.db.models <span class="keyword">import</span> F</span><br><span class="line">  Book.objects.filter(commentNum__lt=F(<span class="string">'keepNum'</span>))</span><br><span class="line"></span><br><span class="line">查询评论数大于收藏数<span class="number">2</span>倍的书籍</span><br><span class="line">Book.objects.filter(commentNum__lt=F(<span class="string">'keepNum'</span>)*<span class="number">2</span>)</span><br><span class="line">Book.objects.all().update(price=F(<span class="string">"price"</span>)+<span class="number">30</span>)</span><br></pre></td></tr></table></figure>

<p>5）Q查询</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">bookList=Book.objects.filter(Q(authors__name=<span class="string">"yuan"</span>)|Q(authors__name=<span class="string">"egon"</span>))</span><br><span class="line">优点：Q查询可以多差嵌套</span><br></pre></td></tr></table></figure>

<h3 id="6-3orm执行原生sql语句"><a href="#6-3orm执行原生sql语句" class="headerlink" title="6.3orm执行原生sql语句"></a>6.3orm执行原生sql语句</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">方式一：</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    first_name = models.CharField(...)</span><br><span class="line">    last_name = models.CharField(...)</span><br><span class="line">    birth_date = models.DateField(...)</span><br><span class="line">　　可以像下面这样执行原生SQL语句</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> p <span class="keyword">in</span> Person.objects.raw(<span class="string">'SELECT * FROM myapp_person'</span>):</span><br><span class="line">    print(p)</span><br><span class="line">方式二：</span><br><span class="line"><span class="keyword">from</span> django.db <span class="keyword">import</span> connection, connections</span><br><span class="line">cursor = connection.cursor()  <span class="comment"># cursor = connections['default'].cursor()</span></span><br><span class="line">cursor.execute(<span class="string">"""SELECT * from auth_user where id = %s"""</span>, [<span class="number">1</span>])</span><br><span class="line">ret = cursor.fetchone()</span><br></pre></td></tr></table></figure>

<h2 id="6-4python文件中调用Djangomodel"><a href="#6-4python文件中调用Djangomodel" class="headerlink" title="6.4python文件中调用Djangomodel"></a>6.4python文件中调用Djangomodel</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> os</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    os.environ.setdefault(<span class="string">"DJANGO_SETTINGS_MODULE"</span>, <span class="string">"BMS.settings"</span>) <span class="comment">#环境</span></span><br><span class="line">    <span class="keyword">import</span> django</span><br><span class="line">    django.setup()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">from</span> app01 <span class="keyword">import</span> models  <span class="comment">#引入也要写在上面三句之后</span></span><br><span class="line"><span class="comment">#上面的格式是固定的</span></span><br><span class="line">    books = models.Book.objects.all()</span><br><span class="line">    print(books)</span><br><span class="line">注意：</span><br><span class="line">　　<span class="number">1</span>、脚本文件必须写在项目文件夹下</span><br></pre></td></tr></table></figure>

<h2 id="七、模板渲染"><a href="#七、模板渲染" class="headerlink" title="七、模板渲染"></a>七、模板渲染</h2><p>1、语法、据点符、</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">语法：</span><br><span class="line">	变量：&#123;&#123;&#125;&#125;</span><br><span class="line">    逻辑：&#123;% %&#125;</span><br><span class="line">据点.符</span><br><span class="line">	字典、对象、列表都可以使用，也可以混着使用</span><br><span class="line">locals()返回的是所有的变量，不建议使用</span><br></pre></td></tr></table></figure>

<p>3、常见的过滤器</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">default    length  filesizeformat slice　date safe truncatechars cut join timesince</span><br><span class="line">timeuntil</span><br></pre></td></tr></table></figure>

<p>4、forloop/if/for/with</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">forloop.counter            当前循环的索引值(从<span class="number">1</span>开始)，forloop是循环器，通过点来使用功能</span><br><span class="line">forloop.counter0           当前循环的索引值（从<span class="number">0</span>开始）</span><br><span class="line">forloop.revcounter         当前循环的倒序索引值（从<span class="number">1</span>开始）</span><br><span class="line">forloop.revcounter0        当前循环的倒序索引值（从<span class="number">0</span>开始）</span><br><span class="line">forloop.first              当前循环是不是第一次循环（布尔值）</span><br><span class="line">forloop.last               当前循环是不是最后一次循环（布尔值）</span><br><span class="line">forloop.parentloop         本层循环的外层循环的对象，再通过上面的几个属性来显示外层循环的计数等</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#123;% <span class="keyword">for</span> person <span class="keyword">in</span> person_list %&#125;</span><br><span class="line">    &lt;p&gt;&#123;&#123; person.name &#125;&#125;&lt;/p&gt;</span><br><span class="line">&#123;% empty %&#125;  <span class="comment">#在 person_list 为空的时候,执行</span></span><br><span class="line">    &lt;p&gt;sorry,no person here&lt;/p&gt;</span><br><span class="line">&#123;% endfor %&#125;  </span><br><span class="line"></span><br><span class="line">&#123;% if user_list|length &gt; 5 %&#125;  &lt;!--结合过滤器来使用--&gt;</span><br><span class="line">  七座豪华SUV</span><br><span class="line">&#123;% <span class="keyword">else</span> %&#125;</span><br><span class="line">    黄包车</span><br><span class="line">&#123;% endif %&#125;</span><br><span class="line"></span><br><span class="line">&#123;% <span class="keyword">with</span> total=business.employees.count %&#125;</span><br><span class="line">    &#123;&#123; total &#125;&#125; &lt;!--只能在with语句体内用--&gt;</span><br><span class="line">&#123;% endwith %&#125;</span><br><span class="line">&#123;% <span class="keyword">with</span> business.employees.count <span class="keyword">as</span> total %&#125;</span><br><span class="line">    &#123;&#123; total &#125;&#125;  &lt;!--只能在with语句体内用--&gt;</span><br><span class="line">&#123;% endwith %&#125;</span><br></pre></td></tr></table></figure>

<p>5、自定义标签和过滤器</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、在settings中的INSTALLED_APPS配置当前app，不然django无法找到自定义的simple_tag</span><br><span class="line"><span class="number">2</span>、在app中创建templatetags模块(模块名只能是templatetags)</span><br><span class="line"><span class="number">3</span>、创建任意 .py 文件，如：my_tags.py</span><br><span class="line"><span class="number">4</span>、在使用自定义simple_tag和filter的html文件中导入之前创建的 my_tags.py</span><br><span class="line"><span class="number">5</span>、使用simple_tag和filter（如何调用）</span><br></pre></td></tr></table></figure>

<p>6、静态文件</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、配置文件的写法</span><br><span class="line">STATIC_URL = <span class="string">'/static/'</span> <span class="comment">#别名</span></span><br><span class="line">STATICFILES_DIRS = [</span><br><span class="line">    os.path.join(BASE_DIR,<span class="string">'jingtaiwenjian'</span>), <span class="comment">#注意别忘了写逗号,第二个参数就是项目中你存放静态文件的文件夹名称</span></span><br><span class="line">]</span><br><span class="line"><span class="number">2</span>、html文件的写法（推荐写法）</span><br><span class="line">&#123;% load static %&#125;</span><br><span class="line">&lt;img src=<span class="string">"&#123;% static "</span>images/hi.jpg<span class="string">" %&#125;"</span> alt=<span class="string">"Hi!"</span> /&gt;</span><br><span class="line"><span class="number">3</span>、还有其他其他两种写法</span><br></pre></td></tr></table></figure>

<h2 id="八、http协议"><a href="#八、http协议" class="headerlink" title="八、http协议"></a>八、http协议</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">1、定义：</span><br><span class="line">	超文本传输协议</span><br><span class="line">2、http请求响应的步骤</span><br><span class="line">	 客户端连接到Web服务器</span><br><span class="line">	 发送HTTP请求</span><br><span class="line">	 服务器接受请求并返回HTTP响应</span><br><span class="line">	 释放连接TCP连接</span><br><span class="line">	 客户端浏览器解析HTML内容\</span><br><span class="line">3、http请求的特点：</span><br><span class="line">	没有状态、没有连接</span><br><span class="line">4、请求方法</span><br><span class="line">	get/head/post/put/delete/options</span><br><span class="line">5、状态码;</span><br><span class="line">	1xx,</span><br><span class="line">	2xx</span><br><span class="line">	3xx</span><br><span class="line">	4xx</span><br><span class="line">	5xx</span><br></pre></td></tr></table></figure>

<h2 id="九、Ajex请求"><a href="#九、Ajex请求" class="headerlink" title="九、Ajex请求"></a>九、Ajex请求</h2><p>1、特点</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1、不重新加载整个页面的情况下，可以与服务器交换数据并更新部分网页内容</span><br><span class="line">2、异步</span><br></pre></td></tr></table></figure>

<p>2、应用场景</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">　1、注册的时候用户名查询</span><br><span class="line">　2、搜索引擎根据用户输入的关键字，自动提示检索关键字</span><br><span class="line">　　当文件框发生了输入变化时，使用AJAX技术向服务器发送一个请求，然后服务器会把查询到的结果响应给浏览器，最后再把后端返回的结果展示出来。整个过程中页面没有刷新，只是刷新页面中的局部位置而已！当请求发出后，浏览器还可以进行其他操作，无需等待服务器的响应！</span><br></pre></td></tr></table></figure>

<h2 id="10、cookie和session"><a href="#10、cookie和session" class="headerlink" title="10、cookie和session"></a>10、cookie和session</h2><h3 id="六-多表查询"><a href="#六-多表查询" class="headerlink" title="六 多表查询"></a>六 多表查询</h3>
      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2019/09/21/【内容回顾】03-2django - 副本/" title="Django">http://yoursite.com/2019/09/21/【内容回顾】03-2django - 副本/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/dxl/tags/面试题/" rel="tag"># 面试题</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/dxl/2019/09/20/【0目录】爬虫学习目录/" rel="next" title>
                <i class="fa fa-chevron-left"></i> 
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/dxl/2019/09/21/【Django】09From表单和ModelForm组件/" rel="prev" title="Form和ModelForm">
                Form和ModelForm <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/dxl/images/avatar.png" alt>
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/dxl/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/dxl/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/dxl/tags/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-sign-out"></i>
                我的友链
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="tencent://message/?Menu=yes&uin=1258517737&Site=QQ%E6%9E%81%E5%AE%A2&Service=300&sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45/" title="申请坑位" target="_blank">申请坑位</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、中间件"><span class="nav-number">1.</span> <span class="nav-text">一、中间件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、url路由"><span class="nav-number">2.</span> <span class="nav-text">二、url路由</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、视图"><span class="nav-number">3.</span> <span class="nav-text">三、视图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五、单标查询"><span class="nav-number">4.</span> <span class="nav-text">五、单标查询</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1概念介绍"><span class="nav-number">4.1.</span> <span class="nav-text">5.1概念介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2操作"><span class="nav-number">4.2.</span> <span class="nav-text">5.2操作</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六、多表查询"><span class="nav-number">5.</span> <span class="nav-text">六、多表查询</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-1表的创建"><span class="nav-number">5.1.</span> <span class="nav-text">6.1表的创建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-2表的基本操作"><span class="nav-number">5.2.</span> <span class="nav-text">6.2表的基本操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-3orm执行原生sql语句"><span class="nav-number">5.3.</span> <span class="nav-text">6.3orm执行原生sql语句</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-4python文件中调用Djangomodel"><span class="nav-number">6.</span> <span class="nav-text">6.4python文件中调用Djangomodel</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#七、模板渲染"><span class="nav-number">7.</span> <span class="nav-text">七、模板渲染</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#八、http协议"><span class="nav-number">8.</span> <span class="nav-text">八、http协议</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#九、Ajex请求"><span class="nav-number">9.</span> <span class="nav-text">九、Ajex请求</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10、cookie和session"><span class="nav-number">10.</span> <span class="nav-text">10、cookie和session</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#六-多表查询"><span class="nav-number">10.1.</span> <span class="nav-text">六 多表查询</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-hand-peace-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/dxl/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/dxl/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/dxl/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/dxl/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/dxl/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/dxl/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '13B0JGDuA6ttduN8AQaR8CzF-gzGzoHsz',
        appKey: 'I13r9r5mVgq4jQYpYy6V4gW3',
        placeholder: '欢迎大佬指点~~~',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
